/*
========================================================================
 Name        : SingaporeBusSettingItemListView.cpp
 Author      : 
 Copyright   : Your copyright notice
 Description : 
========================================================================
*/
// [[[ begin generated region: do not modify [Generated System Includes]
#include <aknviewappui.h>
#include <eikmenub.h>
#include <avkon.hrh>
#include <akncontext.h>
#include <akntitle.h>
#include <stringloader.h>
#include <barsread.h>
#include <eikbtgpc.h>
#include <aknnotewrappers.h>
#include <SingaporeBus.rsg>
// ]]] end generated region [Generated System Includes]

// [[[ begin generated region: do not modify [Generated User Includes]

#include "SingaporeBus.hrh"
#include "SingaporeBusSettingItemListView.h"
#include "PublicTransportMapContainer.hrh"
#include "CSingaporeBusGenericView.hrh"
#include "SingaporeBusSettingItemList.hrh"
#include "SingaporeBusAccessPointsPriorityListBox.hrh"
#include "CSingaporeBusStopsView.hrh"
#include "CSingaporeBusServicesArrivalTimeView.hrh"
#include "CSingaporeBusRouteView.hrh"
#include "CSingaporeBusServiceRouteView.hrh"
#include "CSingaporeBusServicesView.hrh"
#include "CSingaporeBusFavoritesView.hrh"
#include "SingaporeBusSettingItemList.h"
// ]]] end generated region [Generated User Includes]

#include <aknmessagequerydialog.h> //CAknMessageQueryDialog
#include "SingaporeBusDocument.h"
#include "CharUtils.h"
#include <apgcli.h>
#include <euserhl.h>


// [[[ begin generated region: do not modify [Generated Constants]
// ]]] end generated region [Generated Constants]

/**
 * First phase of Symbian two-phase construction. Should not contain any
 * code that could leave.
 */
CSingaporeBusSettingItemListView::CSingaporeBusSettingItemListView()
	{
	// [[[ begin generated region: do not modify [Generated Contents]
	// ]]] end generated region [Generated Contents]
	}

/** 
 * The view's destructor removes the container from the control
 * stack and destroys it.
 */
CSingaporeBusSettingItemListView::~CSingaporeBusSettingItemListView()
	{
	// [[[ begin generated region: do not modify [Generated Contents]
	// ]]] end generated region [Generated Contents]
	
	}

/**
 * Symbian two-phase constructor.
 * This creates an instance then calls the second-phase constructor
 * without leaving the instance on the cleanup stack.
 * @return new instance of CSingaporeBusSettingItemListView
 */
CSingaporeBusSettingItemListView* CSingaporeBusSettingItemListView::NewL()
	{
TFunTrace funTrace(__PRETTY_FUNCTION__);
	CSingaporeBusSettingItemListView* self = CSingaporeBusSettingItemListView::NewLC();
	CleanupStack::Pop( self );
	return self;
	}

/**
 * Symbian two-phase constructor.
 * This creates an instance, pushes it on the cleanup stack,
 * then calls the second-phase constructor.
 * @return new instance of CSingaporeBusSettingItemListView
 */
CSingaporeBusSettingItemListView* CSingaporeBusSettingItemListView::NewLC()
	{
TFunTrace funTrace(__PRETTY_FUNCTION__);
	CSingaporeBusSettingItemListView* self = new ( ELeave ) CSingaporeBusSettingItemListView();
	CleanupStack::PushL( self );
	self->ConstructL();
	return self;
	}


/**
 * Second-phase constructor for view.  
 * Initialize contents from resource.
 */ 
void CSingaporeBusSettingItemListView::ConstructL()
	{
TFunTrace funTrace(__PRETTY_FUNCTION__);
	// [[[ begin generated region: do not modify [Generated Code]
	BaseConstructL( R_SINGAPORE_BUS_SETTING_ITEM_LIST_SINGAPORE_BUS_SETTING_ITEM_LIST_VIEW );
				
	// ]]] end generated region [Generated Code]
	
	}

/**
 * @return The UID for this view
 */
TUid CSingaporeBusSettingItemListView::Id() const
	{
TFunTrace funTrace(__PRETTY_FUNCTION__);
	return TUid::Uid( ESingaporeBusSettingItemListViewId );
	}

/**
 * Handle a command for this view (override)
 * @param aCommand command id to be handled
 */
void CSingaporeBusSettingItemListView::HandleCommandL( TInt aCommand )
	{
	// [[[ begin generated region: do not modify [Generated Code]
	TBool commandHandled = EFalse;
	switch ( aCommand )
		{	// code to dispatch to the AknView's menu and CBA commands is generated here
	
		case EAknSoftkeyDone:
			commandHandled = HandleControlPaneRightSoftKeyPressedL( aCommand );
			break;
		case ESingaporeBusSettingItemListViewMenuItem1Command:
			commandHandled = HandleChangeSelectedSettingItemL( aCommand );
			break;
		case ESingaporeBusSettingItemListViewEnable_logsMenuItemCommand:
			commandHandled = HandleEnable_logsMenuItemSelectedL( aCommand );
			break;
		case ESingaporeBusSettingItemListViewDisable_logsMenuItemCommand:
			commandHandled = HandleDisable_logsMenuItemSelectedL( aCommand );
			break;
		case ESingaporeBusSettingItemListViewClear_tile_cacheMenuItemCommand:
			commandHandled = HandleClearTileCacheMenuItemSelectedL( aCommand );
			break;
		case ESingaporeBusSettingItemListViewCheck_for_updateMenuItemCommand:
			commandHandled = HandleCheckForUpdateMenuItemSelectedL( aCommand );
			break;
		case ESingaporeBusSettingItemListViewAboutMenuItemCommand:
			commandHandled = HandleAboutMenuItemSelectedL( aCommand );
			break;
		case ESingaporeBusSettingItemListViewExitMenuItemCommand:
			commandHandled = HandleExitMenuItemSelectedL( aCommand );
			break;
		default:
			break;
		}
	
		
	if ( !commandHandled ) 
		{
	
		}
	// ]]] end generated region [Generated Code]
	
	}

/**
 *	Handles user actions during activation of the view, 
 *	such as initializing the content.
 */
void CSingaporeBusSettingItemListView::DoActivateL( 
		const TVwsViewId& aPrevViewId,
		TUid /*aCustomMessageId*/,
		const TDesC8& /*aCustomMessage*/ )
	{
TFunTrace funTrace(__PRETTY_FUNCTION__);
	// [[[ begin generated region: do not modify [Generated Contents]
	SetupStatusPaneL();
	
				
	if ( iSingaporeBusSettingItemList == NULL )
		{
		iSettings = TSingaporeBusSettingItemListSettings::NewL();
		iSingaporeBusSettingItemList = new ( ELeave ) CSingaporeBusSettingItemList( *iSettings, this );
		iSingaporeBusSettingItemList->SetMopParent( this );
		iSingaporeBusSettingItemList->ConstructFromResourceL( R_SINGAPORE_BUS_SETTING_ITEM_LIST_SINGAPORE_BUS_SETTING_ITEM_LIST );
		iSingaporeBusSettingItemList->ActivateL();
		iSingaporeBusSettingItemList->LoadSettingValuesL();
		iSingaporeBusSettingItemList->LoadSettingsL();
		AppUi()->AddToStackL( *this, iSingaporeBusSettingItemList );
		} 
	// ]]] end generated region [Generated Contents]
	
	}

/**
 */
void CSingaporeBusSettingItemListView::DoDeactivate()
	{
TFunTrace funTrace(__PRETTY_FUNCTION__);
	// [[[ begin generated region: do not modify [Generated Contents]
	CleanupStatusPane();
	
	if ( iSingaporeBusSettingItemList != NULL )
		{
		AppUi()->RemoveFromStack( iSingaporeBusSettingItemList );
		delete iSingaporeBusSettingItemList;
		iSingaporeBusSettingItemList = NULL;
		delete iSettings;
		iSettings = NULL;
		}
	// ]]] end generated region [Generated Contents]
	
	}

/** 
 * Handle status pane size change for this view (override)
 */
void CSingaporeBusSettingItemListView::HandleStatusPaneSizeChange()
	{
TFunTrace funTrace(__PRETTY_FUNCTION__);
	CAknView::HandleStatusPaneSizeChange();
	
	// this may fail, but we're not able to propagate exceptions here
	TVwsViewId view;
	AppUi()->GetActiveViewId( view );
	if ( view.iViewUid == Id() )
		{
		TInt result;
		TRAP( result, SetupStatusPaneL() );
		}
	
	// [[[ begin generated region: do not modify [Generated Code]
	// ]]] end generated region [Generated Code]
	
	}

// [[[ begin generated function: do not modify
void CSingaporeBusSettingItemListView::SetupStatusPaneL()
	{
	// reset the context pane
	TUid contextPaneUid = TUid::Uid( EEikStatusPaneUidContext );
	CEikStatusPaneBase::TPaneCapabilities subPaneContext = 
		StatusPane()->PaneCapabilities( contextPaneUid );
	if ( subPaneContext.IsPresent() && subPaneContext.IsAppOwned() )
		{
		CAknContextPane* context = static_cast< CAknContextPane* > ( 
			StatusPane()->ControlL( contextPaneUid ) );
		context->SetPictureToDefaultL();
		}
	
	// setup the title pane
	TUid titlePaneUid = TUid::Uid( EEikStatusPaneUidTitle );
	CEikStatusPaneBase::TPaneCapabilities subPaneTitle = 
		StatusPane()->PaneCapabilities( titlePaneUid );
	if ( subPaneTitle.IsPresent() && subPaneTitle.IsAppOwned() )
		{
		CAknTitlePane* title = static_cast< CAknTitlePane* >( 
			StatusPane()->ControlL( titlePaneUid ) );
		TResourceReader reader;
		iEikonEnv->CreateResourceReaderLC( reader, R_SINGAPORE_BUS_SETTING_ITEM_LIST_TITLE_RESOURCE );
		title->SetFromResourceL( reader );
		CleanupStack::PopAndDestroy(); // reader internal state
		}
				
	}

// ]]] end generated function

// [[[ begin generated function: do not modify
void CSingaporeBusSettingItemListView::CleanupStatusPane()
	{
	}

// ]]] end generated function

/** 
 * Handle the selected event.
 * @param aCommand the command id invoked
 * @return ETrue if the command was handled, EFalse if not
 */
TBool CSingaporeBusSettingItemListView::HandleChangeSelectedSettingItemL( TInt aCommand )
	{
TFunTrace funTrace(__PRETTY_FUNCTION__);
	iSingaporeBusSettingItemList->ChangeSelectedItemL();
	return ETrue;
	}
				

/** 
 * Handle the rightSoftKeyPressed event.
 * @return ETrue if the command was handled, EFalse if not
 */
TBool CSingaporeBusSettingItemListView::HandleControlPaneRightSoftKeyPressedL( TInt aCommand )
	{
TFunTrace funTrace(__PRETTY_FUNCTION__);
	// TODO: implement rightSoftKeyPressed event handler
	CSingaporeBusDocument* doc = (CSingaporeBusDocument*)CEikonEnv::Static()->EikAppUi()->Document();
	doc->SaveSettingsL();
	
	AppUi()->HandleCommandL(EAknSoftkeyBack);
	
	return ETrue;
	}
				
/** 
 * Handle the selected event.
 * @param aCommand the command id invoked
 * @return ETrue if the command was handled, EFalse if not
 */
TBool CSingaporeBusSettingItemListView::HandleEnable_logsMenuItemSelectedL( TInt aCommand )
	{

	CSingaporeBusDocument* doc = (CSingaporeBusDocument*)CEikonEnv::Static()->EikAppUi()->Document();
	doc->EnableLogs();	
	return ETrue;
	}
				
/** 
 * Handle the selected event.
 * @param aCommand the command id invoked
 * @return ETrue if the command was handled, EFalse if not
 */
TBool CSingaporeBusSettingItemListView::HandleDisable_logsMenuItemSelectedL( TInt aCommand )
	{
	CSingaporeBusDocument* doc = (CSingaporeBusDocument*)CEikonEnv::Static()->EikAppUi()->Document();
	doc->DisableLogs();
	return ETrue;
	}
				
/** 
 * Handle the selected event.
 * @param aCommand the command id invoked
 * @return ETrue if the command was handled, EFalse if not
 */
TBool CSingaporeBusSettingItemListView::HandleClearTileCacheMenuItemSelectedL( TInt aCommand )
	{
	CSingaporeBusDocument* doc = (CSingaporeBusDocument*)CEikonEnv::Static()->EikAppUi()->Document();
	doc->iMapTileServer->ClearTileCache();
	return ETrue;
	}


_LIT(KApplicationHomePage, "http://projects.developer.nokia.com/SingaporeBus");
_LIT(KPrivacyPolicyHomePage, "http://projects.developer.nokia.com/SingaporeBus/wiki/PrivacyPolicy");
_LIT(KMapQuestHomePage, "http://www.mapquest.com");
_LIT(KOpenStreetMapHomePage, "http://www.openstreetmap.org/");
_LIT(KCCBYSAHomePage, "http://creativecommons.org/licenses/by-sa/2.0/");

LOCAL_C TInt OpenLinkL(TAny* aLink)
	{
	RApaLsSession apaLsSession;
	const TUid KOSSBrowserUidValue = {0x10008D39}; // 0x1020724D for S60 3rd Ed
	RBuf param;
	CleanupClosePushL(param);
	param.CreateL(1024);
	param.Format(_L("4 %S"), aLink);
	TUid id(KOSSBrowserUidValue);
	TApaTaskList taskList(CEikonEnv::Static()->WsSession());
	TApaTask task = taskList.FindApp(id);

	
	
	if(task.Exists())
	    {
		RProcess proc;
		if(proc.HasCapability(ECapabilitySwEvent, NULL))
			{
			task.BringToForeground();
			RBuf8 param8;
			CleanupClosePushL(param8);
			param8.CreateL(param.Length());
			param8.Copy(param);
		    task.SendMessage(TUid::Uid(0), param8); // UID not used
			CleanupStack::PopAndDestroy(&param8);
			}
		else
			{
			CAknErrorNote* msg = new (ELeave) CAknErrorNote(EFalse);
			msg->ExecuteLD(_L("Please close the Web browser and try again"));
			}
	    }
	else
	    {
	    if(!apaLsSession.Handle())
	      {
	      User::LeaveIfError(apaLsSession.Connect());
	      }
	    TThreadId thread;
	    User::LeaveIfError(apaLsSession.StartDocument(param, KOSSBrowserUidValue, thread));
	    apaLsSession.Close();   
	    }
	CleanupStack::PopAndDestroy(&param);
	} 


				
/** 
 * Handle the selected event.
 * @param aCommand the command id invoked
 * @return ETrue if the command was handled, EFalse if not
 */
TBool CSingaporeBusSettingItemListView::HandleAboutMenuItemSelectedL( TInt aCommand )
	{
	
	CAknMessageQueryDialog* dlg = new (ELeave) CAknMessageQueryDialog();
	dlg->PrepareLC(R_SINGAPORE_BUS_ABOUT_QUERY_DIALOG);
	dlg->QueryHeading()->SetTextL(_L("About..."));
	
	TCallBack callback1(OpenLinkL, (TAny*)&KApplicationHomePage());
	dlg->SetLink(callback1);
	dlg->SetLinkTextL(KApplicationHomePage);
	
	_LIT(kNoteFormat, "SingaporeBus %S\n%S binary built on " __DATE__ " at " __TIME__ "\n-\n%S\n");
	
	RBuf noteText;
	CleanupClosePushL(noteText);
	TBuf<128> version;
	version.Append( *narrowToWideLC(_L8(APPLICATION_VERSION) ) );
	CleanupStack::PopAndDestroy();
	TBool versionSuffix = EFalse;
	RProcess proc;
	if(!proc.HasCapability(ECapabilityReadDeviceData, NULL))
		{
		if(!versionSuffix) version.Append(_L("\n("));
		version.Append(_L("NR"));
		versionSuffix = ETrue;
		}
	if(!proc.HasCapability(ECapabilityLocation, NULL))
		{
		if(!versionSuffix) version.Append(_L("\n("));
		version.Append(_L("NL"));
		versionSuffix = ETrue;
		}
	if(!proc.HasCapability(ECapabilitySwEvent, NULL))
		{
		if(!versionSuffix) version.Append(_L("\n("));
		version.Append(_L("NS"));
		versionSuffix = ETrue;		
		}
	if(versionSuffix) version.Append(_L(") "));
	
	TBuf<128> binary;
#ifndef __SERIES60_3X__ // Symbian^3 does not define that macro
	binary.Append(_L("Symbian^3"));
#elif defined(__S60_50__)
	binary.Append(_L("S60 5th Edition"));
#elif defined(__S60_32__)
	binary.Append(_L("S60 3rd Ed FP2"));
#else
	binary.Append(_L("S60 3rd Ed FP1"));
#endif	
	
	noteText.CreateL(1024);
	
	
	noteText.Format(kNoteFormat, &version, &binary, &KApplicationHomePage());

	{
	noteText.AppendFormat(_L("-\nPrivacy Policy"));
	TCallBack callback(OpenLinkL, (TAny*)&KPrivacyPolicyHomePage());
	dlg->SetLink(callback);
	dlg->SetLinkTextL(_L("Privacy Policy"));
	}
	
#ifdef MAPQUEST
	noteText.Append(_L("\n-\nTiles Courtesy of MapQuest\n-\n(c) OpenStreetMap contributors, CC-BY-SA"));
	{
	TCallBack callback(OpenLinkL, (TAny*)&KMapQuestHomePage());
	dlg->SetLink(callback);
	dlg->SetLinkTextL(_L("MapQuest"));
	}
	{
	TCallBack callback(OpenLinkL, (TAny*)&KOpenStreetMapHomePage());
	dlg->SetLink(callback);
	dlg->SetLinkTextL(_L("OpenStreetMap"));
	}
	{
	TCallBack callback(OpenLinkL, (TAny*)&KCCBYSAHomePage());
	dlg->SetLink(callback);
	dlg->SetLinkTextL(_L("CC-BY-SA"));
	}
#endif
	
	dlg->SetMessageTextL(noteText);
	CleanupStack::PopAndDestroy( &noteText );
	
	dlg->RunLD();
		
	return ETrue;
	}
				
// [[[ begin generated function: do not modify
/**
 * Show the popup note for noteAbout
 * @param aOverrideText optional override text
 */
void CSingaporeBusSettingItemListView::RunNoteAboutL( const TDesC* aOverrideText )
	{
	CAknInformationNote* note = new ( ELeave ) CAknInformationNote();
	if ( aOverrideText == NULL )
		{
		HBufC* noteText = StringLoader::LoadLC( R_SINGAPORE_BUS_SETTING_ITEM_LIST_NOTE_ABOUT );
		note->ExecuteLD( *noteText );
		CleanupStack::PopAndDestroy( noteText );
		}
	else
		{
		note->ExecuteLD( *aOverrideText );
		}
	}
// ]]] end generated function

/** 
 * Handle the selected event.
 * @param aCommand the command id invoked
 * @return ETrue if the command was handled, EFalse if not
 */
TBool CSingaporeBusSettingItemListView::HandleExitMenuItemSelectedL( TInt aCommand )
	{
	AppUi()->HandleCommandL( EEikCmdExit );
	return ETrue;
	}
				
/** 
 * Handle the selected event.
 * @param aCommand the command id invoked
 * @return ETrue if the command was handled, EFalse if not
 */
TBool CSingaporeBusSettingItemListView::HandleCheckForUpdateMenuItemSelectedL( TInt aCommand )
	{
	CSingaporeBusDocument* doc = (CSingaporeBusDocument*)CEikonEnv::Static()->EikAppUi()->Document();
	doc->iApplicationUpdater->StartUpdateSequenceL(EFalse, doc);
	return ETrue;
	}
